package net.daum.codegen;

import javax.sql.DataSource;

import net.daum.codegen.dao.SchemaDao;

import org.apache.commons.dbcp.BasicDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperFactoryBean;
import org.springframework.core.io.ClassPathResource;

public class DatabaseUtil {
	private static final String DATABASE_DRIVER = "com.mysql.jdbc.Driver";
	//private static final String DATABASE_URL = "jdbc:mysql://118.218.127.83:3306/auto?autoReconnect=true&useUnicode=true&characterEncoding=utf8&mysqlEncoding=utf8";
	private static final String DATABASE_URL = "jdbc:mysql://localhost:3306/test?autoReconnect=true&useUnicode=true&characterEncoding=utf8&mysqlEncoding=utf8";
	private static final String DATABASE_USER = "daumfn";
	private static final String DATBASE_PASSWORD = "!daumfn";
	
	public static DataSource getDataSource() {
		BasicDataSource dataSource = new BasicDataSource();
		dataSource.setDriverClassName(DATABASE_DRIVER);
		dataSource.setUrl(DATABASE_URL);
		dataSource.setUsername(DATABASE_USER);
		dataSource.setPassword(DATBASE_PASSWORD);
		return dataSource;
	}
	
	public static SchemaDao getDao() {
		BasicDataSource dataSource = new BasicDataSource();
		dataSource.setDriverClassName(DATABASE_DRIVER);
		dataSource.setUrl(DATABASE_URL);
		dataSource.setUsername(DATABASE_USER);
		dataSource.setPassword(DATBASE_PASSWORD);
		
		SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
		sqlSessionFactoryBean.setDataSource(dataSource);
		sqlSessionFactoryBean.setConfigLocation(new ClassPathResource("/MapperConfig.xml"));

		try {
			MapperFactoryBean<SchemaDao> mapperFactoryBean = new MapperFactoryBean<SchemaDao>();
			mapperFactoryBean.setSqlSessionFactory(sqlSessionFactoryBean.getObject());
			mapperFactoryBean.setMapperInterface(SchemaDao.class);
			return mapperFactoryBean.getObject();
		} catch (Exception e) {
		}
		
		return null;
	}
}
